package com.meida.module.bus.provider.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.client.entity.VipType;
import com.meida.module.bus.client.entity.VipUser;
import com.meida.module.bus.provider.service.AppUserExtraService;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * description: 我邀请的用户列表
 * date: 2022年-06月-24日 15:22
 * author: ldd
 */
@Component
public class SelectUserListByInviterIdHandler implements PageInterceptor<AppUser> {

    @Resource
    AppUserService appUserService;

    @Resource
    AppUserExtraService appUserExtraService;

    @Override
    public void prepare(CriteriaQuery<AppUser> cq, PageParams pageParams, EntityMap params) {

        cq.select(AppUser.class, "userId", "nickName", "avatar", "fullName", "createTime");
        cq.select(VipType.class, "vipName", "vipCode", "vipTypeId");
        cq.createJoin(VipUser.class).setJoinAlias("vipUser").setMainField("userId").setJoinField("userId");
        cq.createJoin(VipType.class).setMainAlias("vipUser").setMainField("vipTypeId");
        if (null != cq.getLong("userId") && cq.getLong("userId") > 0) {
            cq.eq("user.inviterId", cq.getLong("userId"));
        } else {
            cq.eq("user.inviterId", OpenHelper.getUserId());
        }
        cq.orderByDesc("user.createTime");

    }

    @Override
    public void complete(CriteriaQuery<AppUser> cq, List<EntityMap> result, EntityMap extra) {
        Long inviterId = (null != cq.getLong("userId") && cq.getLong("userId") > 0) ? cq.getLong("userId") : OpenHelper.getUserId();
        Long parentId = appUserService.getById(inviterId).getInviterId();
        if (parentId != null && parentId > 0) {
            EntityMap inviter = appUserExtraService.getAppUserVipInfo(parentId);
            extra.putAll(inviter);
        }

    }
}
